// Package main
// Created by GoLand
// @User: lenora
// @Date: 2023/11/22
// @Time: 16:46

package main

import "fmt"

func deferReturnV1() int {
	a := 0
	defer func() {
		a = 1
	}()
	return a
	//a = 0
}

func deferReturnV2() (a int) {
	a = 0
	defer func() {
		a = 1
	}()
	return a
	//a = 1
}

func deferClosureLoopV1() {
	for i := 0; i < 10; i++ {
		defer func() {
			println(i)
			fmt.Printf("%p\n", &i)
		}()
	}
	//输出的i全部都为10,i的地址是同一个,每一次循环都被赋予新值

	k := 0
	defer func() {
		println("first:", k)
	}()
	k++
	defer func() {
		println("second:", k)
	}()
	k++
	//两个defer中的k值均为2
}

func deferClosureLoopV2() {
	for i := 0; i < 10; i++ {
		defer func(val int) {
			println(val)
		}(i)
	}
	//	defer加入了参数,执行前参数值已确定好,输出9~0
}

func deferClosureLoopV3() {
	for i := 0; i < 10; i++ {
		//与V1相比,虽然每次打印的都是一个值
		//但是j每次都是被重新定义的值,那么j的地址每次都是不一样的,所以新的j的值是在新的地址上开辟的,
		//那么新的j并不会影响之前的j值,所以打印出来的j值是不一样吗的
		j := i
		defer func() {
			println(j)
			fmt.Printf("%p\n", &j)
		}()
	}

	j := 0
	defer func() {
		println("first:", j)
		fmt.Printf("%p\n", &j)
	}()
	k := 1
	defer func() {
		println("second:", k)
		fmt.Printf("%p\n", &k)
	}()
	l := 2
	defer func() {
		println("third:", l)
		fmt.Printf("%p\n", &l)
	}()
}
